package com.moerae.controller;

import com.alibaba.fastjson.JSON;
import com.moerae.pojo.TbskuPo;
import com.moerae.service.TbskuService;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("es")
public class EsContoller {

    @Autowired
    private TbskuService tbskuService;
    private   RestHighLevelClient client;

    @GetMapping("findAll")
    public List<TbskuPo> findAll(){
        List<TbskuPo> list = tbskuService.list();
        return list;
    }

    @GetMapping("createIndex")
    public String createIndex() throws IOException {
        /**
         * es连接建立
         */
      client=new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("192.168.200.151",9200,"http")));
         //1.获取批量数据
        List<TbskuPo> skulist = tbskuService.list();
         //2.创建BulkRequest对象
        BulkRequest bulkRequest = new BulkRequest();

        //3.建立IndecRequest对象，添加进BulkRequest中
        int i=0;
        int count=0;
        for (TbskuPo tbskuPo : skulist) {
            i++;
            //读取数据
            bulkRequest.add(new IndexRequest("tbskuPo").id(tbskuPo.getId()).source(JSON.toJSONString(tbskuPo), XContentType.JSON));
            if (i==5000){
                //将读取的数据录入
                count++;
                BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
                bulkRequest  = new BulkRequest();
                System.out.println("导入数据成功"+i+"条");
                i=0;
            }
        }
        System.out.println("录入数据量"+count);

        //4.发起请求
        BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        if(!bulkResponse.hasFailures()){
            System.out.println("导入剩余数据成功");
            client.close();
        }
        return bulkResponse.status().toString();
    }
    }

